package com.crm.service.impl.cluePoolManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.crm.common.util.ESUtil;
import com.crm.dao.mapper.cluePoolManager.ClueFollowMapper;
import com.crm.dao.mapper.customMapper.cluePoolManagerCustomMapper.ClueFollowChartMapper;
import com.crm.dao.mapper.customMapper.cluePoolManagerCustomMapper.ClueFollowCustomMapper;
import com.crm.dao.mapper.customMapper.customerContractCustomMapper.CustomerForgetRemindMapper;
import com.crm.model.entity.cluePoolManager.ClueFollow;
import com.crm.model.entity.cluePoolManager.ClueFollowExample;
import com.crm.model.qo.cluePoolManager.ClueFollowQO;
import com.crm.model.vo.cluePoolManager.*;
import com.crm.model.vo.contactManager.ContactReportListVO;
import com.crm.model.vo.contactManager.ContactStatisticsVO;
import com.crm.service.cluePoolManager.ClueFollowDbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ Author ：pym
 * @ Date   ：2021/1/8 13:02
 */
@Service
public class ClueFollowDbServiceImpl implements ClueFollowDbService {

    @Value("${esurl}")
    public String ESurl;

    @Autowired
    ClueFollowCustomMapper clueFollowCustomMapper;


    @Autowired
    ClueFollowMapper clueFollowMapper;

    @Autowired
    CustomerForgetRemindMapper customerForgetRemindMapper;

    @Autowired
    ClueFollowChartMapper clueFollowChartMapper;

    /**
     * 线索池详情-线索清单-跟进记录
     *
     * @param clueId ---线索Id
     * @return
     */
    @Override
    public List<ClueFollowVO> selectClueFollowVOList(String clueId) {
        List<ClueFollowVO> clueFollowVOList = clueFollowCustomMapper.selectClueFollowVOList(clueId);
        return clueFollowVOList;
    }

    /**
     * @return
     * @author wll
     * info 用户模块-我的线索池-线索清单-添加跟进
     */
    @Override
    public Boolean addClueFollow(ClueFollow clueFollow) {
        Boolean result = false;
        int num = clueFollowMapper.insertSelective(clueFollow);
        if (num > 0) {
            ESUtil.syncCpClueFollow(JSON.parseObject(JSON.toJSONString(clueFollow, SerializerFeature.WriteDateUseDateFormat), HashMap.class),ESurl);
            result = true;
        }
        return result;
    }

    @Override
    public long selectClueFollowCountByPoolId(String cluePoolId) {
        ClueFollowExample clueFollowExample = new ClueFollowExample();
        ClueFollowExample.Criteria criteria = clueFollowExample.createCriteria();
        criteria.andCluePoolIdEqualTo(cluePoolId);
        long num = clueFollowMapper.countByExample(clueFollowExample);
        return num;
    }

    /**
     * 线索池详情-线索清单-跟进记录
     *
     * @param clueId ---线索Id
     * @return
     */
    @Override
    public List<ClueFollow> selectClueFollowList(String clueId) {
        ClueFollowExample clueFollowExample = new ClueFollowExample();
        ClueFollowExample.Criteria criteria = clueFollowExample.createCriteria();
        criteria.andClueIdEqualTo(clueId);
        List<ClueFollow> clueFollowList = clueFollowMapper.selectByExample(clueFollowExample);
        return clueFollowList;
    }

    /**
     * @param clueFollow yincuimei合用用户系统-跟进记录-跟进详情页面-可修改跟进详情(备注:如有修改请联调测试这个功能)
     * @return
     * @author wll
     * 修改跟进记录
     */
    @Override
    public Boolean updateClueFollow(ClueFollow clueFollow) {
        return clueFollowMapper.updateByPrimaryKeySelective(clueFollow) > 0;
    }

    /**
     * 客户详情跟进记录
     *
     * @param order
     * @param customerId
     * @return
     */
    @Override
    public List<ClueFollowVO> followVOListByCustomerId(String order, String customerId) {
        ClueFollowQO clueFollowQO = new ClueFollowQO();
        clueFollowQO.setCustomerId(customerId);
        return clueFollowCustomMapper.followVOListByCustomerId(clueFollowQO, order);
    }

    /***
     * @Description:根据客户id查询距离当前半年范围内的跟进记录
     * @Param: customerId 客户id
     * @Author: luojie
     * @Date: 2021/11/11 13:52
     */
    @Override
    public List<ClueFollow> selectClueFollowListByCustomerId(String customerId) {
        //查询当前时间退前半个月
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -6);
        Date month = c.getTime();
        ClueFollowExample clueFollowExample = new ClueFollowExample();
        ClueFollowExample.Criteria criteria = clueFollowExample.createCriteria();
        criteria.andCustomerIdEqualTo(customerId);
        criteria.andCreateTmGreaterThanOrEqualTo(month);
        List<ClueFollow> clueFollowList = clueFollowMapper.selectByExample(clueFollowExample);
        return clueFollowList;
    }

    /**
     * 根据用户id获取跟进记录信息
     *
     * @param accountId
     * @return
     * @author: lixq-f
     */
    @Override
    public List<ForgetCustomerVO> selectForgetRemindMsg(String accountId) {
        List<ForgetCustomerVO> forgetCustomerVOS = customerForgetRemindMapper.selectForgetRemindList(accountId);
        return forgetCustomerVOS;
    }

    /**
     * 用户系统--客户管理>我的客户>跟进记录详情
     *
     * @param clueFollowId ---跟进记录主键
     * @param type         1:单品客户跟进详情
     * @return
     * @author yincuimei
     */
    @Override
    public ClueFollowVO selectClueFollowVOById(String clueFollowId, String type, Integer followWay) {
        return clueFollowCustomMapper.selectClueFollowVOById(clueFollowId, type, followWay);
    }

    /**
     * 联系人详情-跟进记录查询-通过联系人id
     *
     * @param contactId 联系人id
     * @param dateUnit  本周 1 本月 2
     * @return
     */
    @Override
    public List<ContactDetailFollowVO> selectFollowByContactId(String contactId, Integer dateUnit) {
        List<ContactDetailFollowVO> clueFollowList = clueFollowCustomMapper.selectFollowByContactId(contactId, dateUnit);
        return clueFollowList;
    }

    /**
     * 根据跟进记录id查询跟进记录信息
     *
     * @param clueFollowId 根据记录id
     * @return
     */
    @Override
    public ClueFollow selectClueFollowById(String clueFollowId) {
        ClueFollow clueFollow = clueFollowMapper.selectByPrimaryKey(clueFollowId);
        return clueFollow;
    }

    /**
     * 跟进记录
     *
     * @param clueFollowQO
     * @param sortOrder
     * @param dateUnit     1今天 2本周 3本月 4本年
     * @return
     */
    @Override
    public List<ClueFollowVO> selectClueFollowPageList(ClueFollowQO clueFollowQO, String sortOrder, Integer dateUnit) {
        return clueFollowCustomMapper.selectClueFollowPageList(clueFollowQO, sortOrder, dateUnit);
    }

    /**
     * 根据日期获取当前
     *
     * @param planDate
     * @return
     */
    @Override
    public List<Integer> getFollowCountByPlanDate(String planDate, String accountId, String startDate, String endDate) {
        return clueFollowCustomMapper.getFollowCountByPlanDate(planDate, accountId, startDate, endDate);
    }

    /**
     * 图表数据获取
     *
     * @param dateUnit---本周1/本月2/上月3
     * @param startTime              开始日期
     * @param endTime                结束日期
     * @return
     * @Author renshaorong
     * @Date 2021/4/12
     */
    @Override
    public List<ClueFollowChartVO> selectClueFollowChartVOList(int dateUnit, Date startTime, Date endTime, String userAccountId) {
        return clueFollowChartMapper.selectClueFollowChartVOList(dateUnit, startTime, endTime, userAccountId);
    }

    @Override
    public List<ClueFollowChartVO> selectAdminClueFollowChartVOList(String startTime, String endTime, String companyId) {
        List<ClueFollowChartByAdminVO> clueFollowChartByAdminVOS = clueFollowChartMapper.selectAdminClueFollowChartVOList(startTime, endTime, companyId);

        Map<String, List<ClueFollowChartByAdminVO>> collect = clueFollowChartByAdminVOS
                .stream()
                .collect(Collectors.groupingBy(ClueFollowChartByAdminVO::getFollowWay));


        List<ClueFollowChartVO> clueFollowChartVOS = new ArrayList<>();
        for (Map.Entry<String, List<ClueFollowChartByAdminVO>> cc : collect.entrySet()) {
            ClueFollowChartVO chartVO = new ClueFollowChartVO();
            chartVO.setType(cc.getKey());
            List<ClueFollowChartByAdminVO> value = cc.getValue();
            Map<String, List<ClueFollowChartByAdminVO>> productMap = value.stream()
                    .collect(Collectors.groupingBy(ClueFollowChartByAdminVO::getProductType));

            List<ClueFollowChartByAdminVO> member = productMap.get("member");
            chartVO.setMember(member != null ? member.size() : 0);

            List<ClueFollowChartByAdminVO> nonMembers = productMap.get("nonMembers");
            chartVO.setNonMembers(nonMembers != null ? nonMembers.size() : 0);

            Map<String, List<ClueFollowChartByAdminVO>> purposeMap = value.stream()
                    .collect(Collectors.groupingBy(ClueFollowChartByAdminVO::getPurposeType));

            List<ClueFollowChartByAdminVO> process = purposeMap.get("process");
            chartVO.setProcess(process != null ? process.size() : 0);
            List<ClueFollowChartByAdminVO> business = purposeMap.get("business");
            chartVO.setBusiness(business != null ? business.size() : 0);
            chartVO.setSum(cc.getValue().size());

            clueFollowChartVOS.add(chartVO);
        }
        return clueFollowChartVOS;
    }

    /**
     * 获取时间列表（折线图X轴）
     *
     * @param dateUnit
     * @param startTime
     * @param endTime
     * @return
     * @Author renshaorong
     * @Date 2021/4/13
     */
    @Override
    public List<String> getTimeList(Integer dateUnit, Date startTime, Date endTime) {
        return clueFollowChartMapper.getTimeList(dateUnit, startTime, endTime);
    }

    /**
     * 获取跟进次数列表（折线图）
     *
     * @param dateUnit
     * @param startTime
     * @param endTime
     * @param type      跟进类型
     * @return
     * @Author renshaorong
     * @Date 2021/4/13
     */
    @Override
    public List<Integer> getFollowWayDataList(Integer dateUnit, Date startTime, Date endTime, Integer type, String userAccountId) {
        return clueFollowChartMapper.getFollowWayDataList(dateUnit, startTime, endTime, type, userAccountId);
    }

    /**
     * 总跟进次数饼状图数据获取
     *
     * @param dateUnit---本周1/本月2/上月3
     * @param startTime              开始日期
     * @param endTime                结束日期
     * @return
     */
    @Override
    public List<Map> getNumPieData(Integer dateUnit, Date startTime, Date endTime, String userAccountId) {
        return clueFollowChartMapper.getNumPieData(dateUnit, startTime, endTime, userAccountId);
    }

    /**
     * 总跟进次数饼状图数据获取
     *
     * @return
     */
    @Override
    public List<Map> getAdminNumPieData(String startTime, String endTime, String userAccountId) {
        return clueFollowChartMapper.getAdminNumPieData(startTime, endTime, userAccountId);
    }

    /**
     * 获取商机状态饼状图数据
     *
     * @param dateUnit
     * @param startTime
     * @param endTime
     * @param type      跟进类型
     * @return
     */
    @Override
    public List<Map<String, Object>> getBusinessStatusData(Integer dateUnit, Date startTime, Date endTime, Integer type, String userAccountId) {
        return clueFollowChartMapper.getBusinessStatusData(dateUnit, startTime, endTime, type, userAccountId);
    }

    /**
     * 获取过程状态饼状图数据
     *
     * @param dateUnit
     * @param startTime
     * @param endTime
     * @param type      跟进类型
     * @return
     */
    @Override
    public List<Map<String, Object>> getProcessStatusData(Integer dateUnit, Date startTime, Date endTime, Integer type, String userAccountId) {
        return clueFollowChartMapper.getProcessStatusData(dateUnit, startTime, endTime, type, userAccountId);
    }
    @Override
    public List<Map<String, Object>> getAdminProcessStatusData( String startTime, String endTime, Integer type, String userAccountId) {
        return clueFollowChartMapper.getAdminProcessStatusData(startTime, endTime, type, userAccountId);
    }

    /**
     * 查询联系人最新的一条跟进记录
     *
     * @param contactId 联系人id
     * @return
     */
    @Override
    public List<ClueFollow> getClueFollowByContactId(String contactId) {
        ClueFollowExample clueFollowExample = new ClueFollowExample();
        clueFollowExample.setOrderByClause("create_tm desc");
        ClueFollowExample.Criteria criteria = clueFollowExample.createCriteria();
        criteria.andContactIdEqualTo(contactId);
        List<ClueFollow> clueFollowList = clueFollowMapper.selectByExample(clueFollowExample);
        return clueFollowList;
    }


    /**
     * @Description: 按天统计时间段内跟进次数
     * @Param: [startTime, endTime]
     * @Return: java.util.List<com.crm.model.vo.contactManager.ContactStatisticsVO>
     * @Author: lixq-f
     * @Date: 2021/4/16
     **/
    @Override
    public List<ContactStatisticsVO> statisticsFollowTimesByDay(String startTime, String endTime,
                                                                String accountId) {
        return clueFollowCustomMapper.statisticsFollowTimesByDay(startTime, endTime,accountId);
    }


    @Override
    public List<ContactStatisticsVO> statisticsFollowTimesByMonth(int thisYear, String accountId) {
        return clueFollowCustomMapper.statisticsFollowTimesByMonth(thisYear, accountId);
    }


    @Override
    public List<ContactReportListVO> getContactReportList(String accountId, String startTime, String endTime) {
        return clueFollowCustomMapper.getContactReportList(accountId, startTime, endTime);
    }

    /**
     * 单品客户跟进记录
     *
     * @param order                   排序
     * @param singleProductCustomerId 单品客户ID
     * @param accountId               账号ID
     * @return {@link {java.util.List<com.crm.model.vo.cluePoolManager.ClueFollowVO>}}
     */
    @Override
    public List<ClueFollowVO> selectClueFollowListByCustomerId(String order, String singleProductCustomerId, String accountId) {
        return clueFollowCustomMapper.selectClueFollowListByCustomerId(order, singleProductCustomerId, accountId);
    }

    /**
     * 根据是否有跟进记录判断是否可删除
     *
     * @param cpFollowPlanId
     * @return
     * @Author renshaorong
     * @Date 2021/5/27
     */
    @Override
    public Integer canBeDelete(String cpFollowPlanId) {
        return clueFollowCustomMapper.canBeDelete(cpFollowPlanId);
    }


    /**
     * @Description: 批量插入跟进记录
     * @Param: [followList]
     * @Return: java.lang.Integer
     * @Author: lixq-f
     * @Date: 2021/6/8
     **/
    @Override
    public Integer batchInsert(List<ClueFollow> followList) {
//        clueFollowCustomMapper
        return null;
    }

    /**
     * 根据创建时间和跟进详情和跟进人id匹配
     * @param createTm
     * @param followDetail
     * @param accountId
     * @return
     */
    @Override
    public ClueFollowVO selectClueFollow(String createTm, String followDetail, String accountId, String customerId) {
        return clueFollowCustomMapper.selectClueFollow(createTm, followDetail, accountId, customerId);
    }

    /**
     * 插入跟进记录
     * @param clueFollow
     * @return
     */
    @Override
    public boolean insertFollow(ClueFollow clueFollow) {
        return clueFollowMapper.insertSelective(clueFollow) > 0;
    }

    @Override
    public List<ClueFollowVO> selectClueFollowWayIsNull() {
        return clueFollowCustomMapper.selectClueFollowWayIsNull();
    }

    /**
     * 通过跟进id查找呼叫表中的通话记录url
     *
     * @param followId
     * @return
     * @Author renshaorong
     * @Date 2021/8/23
     */
    @Override
    public String getCallRecordByFollowId(String followId) {
        return clueFollowCustomMapper.getCallRecordByFollowId(followId);
    }


    /**
     * 根据时间轴、归属公司Id、跟进类型 查询跟进统计
     *
     * @param startTime 时间轴开始
     * @param endTime   时间轴结束
     * @param type      跟进类型
     * @param companyId 归属公司Id
     * @return
     */
    @Override
    public List<Integer> getFollowWayDataListByCompanyId(String startTime, String endTime, Integer type, String companyId) {

        return clueFollowChartMapper.getFollowWayDataListByCompanyId(startTime, endTime, type, companyId);
    }
}
